package com.sky.controller.user;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    @GetMapping("/list")
    public Result<List<AddressBook>> getAddressList() {
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        List<AddressBook> list = addressBookService.getAddressList(addressBook);
        return Result.success(list);
    }

    @PostMapping
    public Result addAddress(@RequestBody AddressBook addressBook) {
        addressBookService.addAddress(addressBook);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<AddressBook> getAddress(@PathVariable Integer id) {
        AddressBook addressBook = addressBookService.getAddress(id);
        return Result.success(addressBook);
    }

    @PutMapping
    public Result updateAddress(@RequestBody AddressBook addressBook){
        addressBookService.updateAddress(addressBook);
        return Result.success();
    }

    @PutMapping("/default")
    public Result setDefaultAddress(@RequestBody AddressBook addressBook){
        addressBookService.setDefaultAddress(addressBook);
        return Result.success();
    }

    @DeleteMapping
    public Result deleteAddress(Long id){
        addressBookService.deleteAddress(id);
        return Result.success();
    }

    @GetMapping("default")
    public Result<AddressBook> getDefaultAddress(){
        AddressBook addressBook= addressBookService.getDefaultAddress();
        if(addressBook==null){
            return Result.error("没有查询到默认地址");
        }
        return Result.success(addressBook);
    }

}
